﻿using System;
using System.Text.RegularExpressions;
using System.Web;

namespace PmfWeb.Core.HttpHandlers
{
    ///<summary>
    /// sql过滤
    ///</summary>
    public class SqlModule : IHttpModule
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += beginRequest;
        }

        private void beginRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication) sender).Context;
            string getkeys = "";
            string keyvalue = "";
            //url提交数据
            if (context.Request.QueryString != null)
            {
                for (int i = 0, j = context.Request.QueryString.Count; i < j; i++)
                {
                    getkeys = context.Request.QueryString.Keys[i];
                    keyvalue = context.Server.UrlDecode(context.Request.QueryString[getkeys]);

                    if (!CheckStr(keyvalue))
                    {
                        context.Response.Redirect("error.aspx");
                        context.Response.End();
                        break;
                    }
                }
            }
            //表单提交数据
            if (context.Request.Form != null)
            {
                for (int i = 0, j = context.Request.Form.Count; i < j; i++)
                {
                    getkeys = context.Request.Form.Keys[i];
                    keyvalue = context.Server.HtmlDecode(context.Request.Form[i]);
                    if (getkeys == "__VIEWSTATE") continue;
                    if (!CheckStr(keyvalue))
                    {
                        context.Response.Redirect("error.aspx");
                        context.Response.End();
                        break;
                    }
                }
            }

        }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
        
        }
        /// <summary>
        /// 用户输入的字符串检查
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <returns>通过返回1,不通过返回小于0</returns>
        public static bool CheckStr(string str)
        {
            string reg =
                @"insert |delete |count\(|asc\(|mid\(|char\(|exec master|net user|net localgroup administrators|or |and |update|drop table|truncate|xp_cmdshell|create |alert |'";
            Regex check = new Regex(reg, RegexOptions.IgnoreCase);
            Match lCheck = check.Match(str);
            return !lCheck.Success;
        }

    }
}
